package com.gzc.just.play.last.war.balanceserver;

import com.gzc.just.play.last.war.common.handler.VirtualThreadNettyServer;
import com.gzc.just.play.last.war.common.handler.VirtualThreadServerFramework;
import com.gzc.just.play.last.war.balanceserver.handler.*;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * Balance Server的Netty服务器实现
 * 使用虚拟线程处理负载均衡请求
 */
@Component("balanceNettyServer")
public class BalanceNettyServer extends VirtualThreadNettyServer {
    private static final Logger logger = LoggerFactory.getLogger(BalanceNettyServer.class);
    
    @Value("${balance.server.port:7001}")
    private int balanceServerPort;
    
    @Value("${balance.server.host:127.0.0.1}")
    private String balanceServerHost;
    
    @Autowired
    private ApplicationContext applicationContext;
    
    public BalanceNettyServer() {
        logger.info("BalanceNettyServer bean is being constructed");
    }
    
    @Override
    protected int getNettyPort() {
        return balanceServerPort;
    }
    
    @Override
    protected String getNettyHost() {
        return balanceServerHost;
    }
    
    @Override
    protected VirtualThreadServerFramework.ServerType getServerType() {
        return VirtualThreadServerFramework.ServerType.BALANCE_SERVER;
    }
    
    @Override
    protected void initializeHandlers() {
        try {
            // 从Spring容器中获取Bean，而不是直接new
            if (applicationContext != null) {
                ServerStatusHandler serverStatusHandler = applicationContext.getBean(ServerStatusHandler.class);
                framework.registerHandler(serverStatusHandler);
                
                LoadBalanceHandler loadBalanceHandler = applicationContext.getBean(LoadBalanceHandler.class);
                framework.registerHandler(loadBalanceHandler);
                
                ServerListHandler serverListHandler = applicationContext.getBean(ServerListHandler.class);
                framework.registerHandler(serverListHandler);
                
                HealthCheckHandler healthCheckHandler = applicationContext.getBean(HealthCheckHandler.class);
                framework.registerHandler(healthCheckHandler);
                
                logger.info("Initialized {} handlers for Balance Server from Spring context", framework.getHandlerManager().getHandlerCount());
            } else {
                logger.warn("ApplicationContext not available, using direct instantiation for handlers");
                // 降级方案
                framework.registerHandler(new ServerStatusHandler());
                framework.registerHandler(new LoadBalanceHandler());
                framework.registerHandler(new ServerListHandler());
                framework.registerHandler(new HealthCheckHandler());
                
                logger.info("Initialized {} handlers for Balance Server using direct instantiation", framework.getHandlerManager().getHandlerCount());
            }
        } catch (Exception e) {
            logger.error("Error initializing Balance Server handlers", e);
            throw new RuntimeException("Failed to initialize Balance Server handlers", e);
        }
    }
    
    @Override
    protected void onConnectionActive(ChannelHandlerContext ctx) {
        super.onConnectionActive(ctx);
        // Balance Server特有的连接处理逻辑
        logger.debug("New balance connection from: {}", ctx.channel().remoteAddress());
    }
    
    @Override
    protected void onConnectionInactive(ChannelHandlerContext ctx) {
        super.onConnectionInactive(ctx);
        // Balance Server特有的连接关闭处理逻辑
        logger.debug("Balance connection closed from: {}", ctx.channel().remoteAddress());
    }
}
